﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace BadHabit.Factory.Windows {

    /// <summary>
    /// Interaction logic for TeamMemberManager.xaml
    /// </summary>
    public partial class TeamMemberManager : BadHabit.WPFTools.ShapedWindow {

        private WPFTools.DelayFilter delayFilter;
        
        private Data.TeamDataSet dsTeam = new BadHabit.Factory.Data.TeamDataSet();
        private BindingListCollectionView View;

        public TeamMemberManager(bool isClientManagement) {
            InitializeComponent();
            
            teamMemberDetail.IsClientManagement = isClientManagement;            
            teamMemberDetail.IsReadingFromMSExchange = IsReadingProductOwnersFromMsExchange;
        }

        protected void TeamMemberManager_Loaded(object sender, RoutedEventArgs e) {
            Client.FactoryMainWindow.IsPopUpOpened = true;

            Client.LoadBacklogUnits();

            if (teamMemberDetail.IsClientManagement)
                SetClientFormVisibility();
            else
                SetMemberFormVisibility();
                
                     
            delayFilter = new WPFTools.DelayFilter(1, ApplyFilter);
            Bind();
        }


        private void SetClientFormVisibility() {
            this.Title = Properties.Resources.Client_Contacts;            
            userRolesGroupBox.Visibility = Visibility.Collapsed;

            if (clientComboBox.Items.Count > 0)
                clientComboBox.SelectedIndex = 0;             
        }

        private void SetMemberFormVisibility() {
            clientComboBox.Visibility = Visibility.Collapsed;
        }

        private bool IsReadingProductOwnersFromMsExchange {
            get {
                bool isReading = false;
                try {
                    isReading = Client.Service.IsReadingClientContactsFromMsExchange();
                } catch (Exception ex) {
                    Windows.Error.ShowError(ex, Properties.Resources.COULD_NOT_READ_PRODUCT_OWNER_REPOSITORY_SETTINGS);
                }
                return isReading;
            }
        }

        private void Bind() {

            if (Client.TeamMemberDataSet == null)
                return;

            // need to put this into a new dataset...dont know why
            dsTeam = new BadHabit.Factory.Data.TeamDataSet();
            if (!teamMemberDetail.IsClientManagement)
                dsTeam.Merge(Client.TeamMemberDataSet.Member);
            else {
                try {
                    if(clientComboBox.SelectedValue!=null)
                        dsTeam.Merge(Client.Service.RetriveMembersByCompany(clientComboBox.SelectedValue.ToString()));
                } catch (Exception ex) {
                    Windows.Error.ShowError(ex, Properties.Resources.COULD_NOT_READ_CLIENTS);
                }
            }
            
            // creates the view            
            View = new System.Windows.Data.BindingListCollectionView(dsTeam.DefaultViewManager.CreateDataView(dsTeam.Member));
            View.SortDescriptions.Add(new System.ComponentModel.SortDescription("NickName", System.ComponentModel.ListSortDirection.Ascending));            

            // sets the datacontext
            DataContext = View;
        }



        private void ApplyFilter() {            
            if (View == null)
                return;
            
            
            View.CustomFilter = "NickName like '%" + searchTextBox.Text + "%' OR DefaultUnitName like '" + searchTextBox.Text + "%' OR MemberId like '" + searchTextBox.Text + "%'";
        }


        protected override void OnClosed(EventArgs e) {
            base.OnClosed(e);
            if (Client.FactoryMainWindow != null)
                Client.FactoryMainWindow.IsPopUpOpened = false;
        }

        private void Save_Executed(object sender, ExecutedRoutedEventArgs e) {
            System.Data.DataTable changes = dsTeam.Member.GetChanges();
            if ( !Client.UserIsInRole(TeamRoles.FACTORY_OWNER) || changes == null || changes.Rows.Count==0) {
                Close();
                return;
            }

            Save(changes);

            Close();
        }


        private void Save(System.Data.DataTable changes) {
            System.Data.DataSet dsChanges = new System.Data.DataSet();
            dsChanges.Merge(changes);


            try {
                Client.Service.SaveTeamMemberList(Client.ConvertToProxyTeamDataSet(dsChanges));
                dsTeam.AcceptChanges();
            } catch (Exception ex) {
                Windows.Error.ShowError(ex, Properties.Resources.COULD_NOT_UPDATE_TEAM_MEMBERS);
                return;
            }

            // re connects
            Client.Connect(true);

        }

        private void Undo_Executed(object sender, ExecutedRoutedEventArgs e) {
            dsTeam.Member.RejectChanges();
            Close();
        }

        private void searchTextBox_SelectionChanged(object sender, RoutedEventArgs e) {
            delayFilter.StartFilter();
        }

        private void addMemberButton_Click(object sender, RoutedEventArgs e) {
            AddNewMember();
        }

        private void AddNewMember() {

            if (IsReadingProductOwnersFromMsExchange && teamMemberDetail.IsClientManagement) {
                Windows.Error.ShowAlert(Properties.Resources.You_can_not_add_exchange_contact);
                return;
            }

            // adds new item
            System.Data.DataRowView memberRowView = (System.Data.DataRowView)View.AddNew();            
            View.CommitNew();

            memberRowView = (System.Data.DataRowView)View.CurrentItem;
            View.EditItem(memberRowView);
            Data.TeamDataSet.MemberRow memberRow = Helper.GetRowFromRowView<Data.TeamDataSet.MemberRow>(memberRowView);

            if (teamMemberDetail.IsClientManagement) {
                memberRow.ClientContactRole = true;
                memberRow.DefaultUnitName = String.Empty;
                memberRow.NickName = Properties.Resources.New_Client_Contact;
                if (clientComboBox.SelectedValue != null)
                    memberRow.Company = clientComboBox.SelectedValue.ToString();
                else
                    memberRow.Company = Properties.Resources.New_Client_Company;
                
            } else {                                
                memberRow.NickName = Properties.Resources.New_Member;                
            }

            View.CommitEdit();
            
            teamMemberListBox.ScrollIntoView(memberRowView);
        }

        private void teamMemberListBox_KeyUp(object sender, KeyEventArgs e) {
            if (e.Key == Key.Delete) {
                if (teamMemberListBox.SelectedItem == null)
                    return;

                if (!Client.UserIsInRole(TeamRoles.FACTORY_OWNER))
                    return;

                Data.TeamDataSet.MemberRow memberRow = Helper.GetRowFromRowView<Data.TeamDataSet.MemberRow>(teamMemberListBox.SelectedItem);
                RemoveMember(memberRow);
            }
        }

        private void RemoveMember(Data.TeamDataSet.MemberRow memberRow) {
            
            if (memberRow == null)
                return;

            MessageBoxResult d = Windows.Error.ShowDialog(
                String.Format(Properties.Resources.Are_you_sure_you_want_to_delete_NICKNAME_member, memberRow.NickName), Properties.Resources.Delete_Member,
                MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
            if (d == MessageBoxResult.No)
                return;


            memberRow.Delete();

            
        }

       


        

        private void clientComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
            if (e.RemovedItems.Count == 0)
                return;
            string oldCompany = e.RemovedItems[0].ToString();
            System.Data.DataTable changes = dsTeam.Member.GetChanges();
            if (changes != null && !IsReadingProductOwnersFromMsExchange) {
                MessageBoxResult d = Windows.Error.ShowDialog(
                    String.Format(Properties.Resources.Save_COMPANY_contacts, oldCompany), Properties.Resources.Save_Contacts
                    , MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes);                
                if (d == MessageBoxResult.Yes)
                    Save(changes);
            }

            Bind();
        }

        
    }
}
